package com.litidea.commons.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.litidea.dataobjects.MenuExtendDO;
import com.litidea.dataobjects.MenuNodeDO;

public class MenuUtils {
	
	/**
     * 转换所有的菜单列表
     * @param menus
     * @return
     */
    public static List<MenuNodeDO> convertMenus(List<? extends MenuNodeDO> menus , int nowLevel) {
        List<MenuNodeDO> responseMenus = new ArrayList<MenuNodeDO>();
        Map<Integer,MenuNodeDO> existsMenus = new HashMap<Integer,MenuNodeDO>(menus.size() * 4 / 3 + 1);
        for(MenuNodeDO menuNodeDO : menus) {
            if(menuNodeDO.getLevelId() == nowLevel) {
                 responseMenus.add(menuNodeDO);
            }else if(menuNodeDO.getLevelId() > nowLevel) {
                MenuNodeDO parent = existsMenus.get(menuNodeDO.getParentId());
                if(parent != null) {
                    parent.addChild(menuNodeDO);
                }
            }
            existsMenus.put(menuNodeDO.getId() , menuNodeDO);
        }
        return responseMenus;
    }
    
    /**
     * 转换所有的菜单列表
     * @param menus
     * @param nowLevel
     * @param allUserMenus
     * @return
     */
    public static List<MenuExtendDO> convertMenus(List<MenuNodeDO> menus , int nowLevel , Map<String , Integer>allUserMenus) {
        List<MenuExtendDO> responseMenus = new ArrayList<MenuExtendDO>();
        Map<Integer,MenuExtendDO> existsMenus = new HashMap<Integer,MenuExtendDO>(menus.size() * 4 / 3 + 1);
        for(MenuNodeDO menuNodeDO : menus) {
            String menuId = String.valueOf(menuNodeDO.getId());
            MenuExtendDO menuExtendDO = new MenuExtendDO();
            if(allUserMenus.containsKey(menuId)) menuExtendDO.setChecked(true);
            try {
                BeanUtils.copyProperties(menuExtendDO , menuNodeDO);
            } catch (Exception e) {}
            if(menuNodeDO.getLevelId() == nowLevel) {
                 responseMenus.add(menuExtendDO);
            }else if(menuNodeDO.getLevelId() > nowLevel) {
                MenuExtendDO parent = existsMenus.get(menuNodeDO.getParentId());
                if(parent != null) {
                    parent.addChild(menuExtendDO);
                }
            }
            existsMenus.put(menuNodeDO.getId() , menuExtendDO);
        }
        return responseMenus;
    }

}
